package com.dongdong.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @Deacription TODO
 * @Author Lenovo
 * @Date 2020/12/13 16:42
 * @Version 1.0
 **/
@Controller
public class IndexController {

//    @RequestMapping({"index","/"})
//    public String index(){
//        return "admin/index";
//    }
//
//    @RequestMapping("home")
//    public String home(){
//        return "admin/home";
//    }

    @RequestMapping("login")
    public String toLogin(String name, String password, Model model){
        //获取用户主体 subject
        Subject subject = SecurityUtils.getSubject();
        //将表单提交的账号和密码封装成token对象
        UsernamePasswordToken token = new UsernamePasswordToken(name,password);
        //执行登陆逻辑
        try {
            subject.login(token);
        }catch (UnknownAccountException e){
            model.addAttribute("message","账号不存在");
            //返回登录页面
            return "login";
        }catch (IncorrectCredentialsException exception){
            model.addAttribute("message","密码错误");
            //返回登录页面
            return "login";
        }
        return "redirect:/index";
    }

    @RequestMapping("home")
    public String home(){

        return "admin/home";
    }

    @RequestMapping({"toLogin","/"})
    public String toLogin(){
        return "shoplogin";
    }

    @RequestMapping("index")
    public String index(){
        return "admin/index";
    }

    @RequestMapping("unauthorized")
    public String unauthorized(){
        return "unauthorized";
    }

    @RequestMapping("toRegister")
    public String toRegister(){
        return "register";
    }
}

